# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.manhuatai.com/[\w\d]+/ 解析器
#
#*******************************************************************************
from base import *

tag='manhuatai'

#---------------------------- 验证模块 ----------------------------

# 每个解析模块都含有这个函数，用来判断链接是否符合该模块
def url_judgement(url):
    if re.match(r'http://www.manhuatai.com/[\w\d]+/',url):
        return valid_check(url)
    return False

# 根据内容检测是否可解析
def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

# 下载器获取
def get_loader(url):
    return ManhuataiLoader(url,ManhuataiPageParser,ManhuataiVolParser)

#---------------------------- 下载器 ----------------------------

class ManhuataiLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class ManhuataiPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<meta property="og:title" content="(.*?)">').findall(content)[0].rstrip()
        # descripiton
        self.comic.description=re.compile(r'<div class="wz clearfix t1"><div>(.*?)<',re.S|re.M).findall(content)[0].strip()
        # cover
        cover_content=re.compile(r'<div class="mhjsbody clearfix">(.*?)<div',re.S).findall(content)[0]
        cover=re.compile(r'src="(.*?)"',re.S).findall(cover_content)[0]
        self.comic.cover=cover
        # vols
        vols_content=re.compile(r'<div class="mhlistbody">(.*?)</div>',re.S|re.M).findall(content)[0]
        self.feed(vols_content)
    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append(InfoVol(self.comic_url+infos['href'],infos['title']))

class ManhuataiVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    def work(self,content):
        mh_info=re.compile(r'var mh_info={(.*?)};').findall(content)[0]
        pages=int(re.compile(r'totalimg:(.*?),').findall(mh_info)[0])
        domain=re.compile(r'domain:"(.*?)"').findall(mh_info)[0]
        image_path=re.compile(r'imgpath:"(.*?)"').findall(mh_info)[0]
        img_path=[]
        for c in image_path:
            img_path.append(chr(ord(c)-4))
        image_path=''.join(img_path)
        image_prefix='http://mhpic.'+domain+'/comic/'+image_path
        for idx in range(1,pages+1):
            url=image_prefix+str(idx)+'.jpg'
            self.pic_urls.append((url,zero_prefix(idx)))